package net.example.activity;

import android.app.Activity;
import android.os.Bundle;

import net.example.manager.ClientGlobalCache;
import net.example.model.event.RequestEvent;
import net.example.model.event.UserEvent;
import net.example.manager.Manager;
import net.example.model.UserStatus;
import net.example.ggtalk.R;
import android.os.Handler;
import android.os.SystemClock;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.oraycn.esbasic.helpers.StringHelper;
import com.oraycn.esframework.core.ClientType;
import com.oraycn.omcs.MultimediaManagerFactory;
import com.oraycn.omcs.core.MicrophoneConnector;
import net.example.model.event.CallEvent;
import net.example.manager.GGApplication;
import net.example.model.CommunicateMediaType;
import net.example.model.CommunicateType;
import net.example.model.GGUser;
import net.example.utils.HeadImgHelper;
import net.example.utils.ToastUtils;
import net.example.utils.android.AndroidUtil;
import java.util.Date;

import de.greenrobot.event.EventBus;

public class VoiceCallActivity extends Activity  {
	LinearLayout coming_callLayout = null,layout_handsfree,layout_mute;
	TextView nameTextView = null, tv_tips;
	ImageView headerImageView = null;
	ImageView iv_mute, iv_handFree;
	Button hangup, pickup, refuse;
	MicrophoneConnector microphoneConnector;
	String userId = "";
	String loginID = "";
	ClientType clientType;
	Chronometer call_time;
	int currVolume = 0;
	public  boolean isRequest;
	public boolean isCall;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat_voicecall);
		if (!EventBus.getDefault().isRegistered(this)) {
			EventBus.getDefault().register(this);
		}
		MultimediaManagerFactory.GetSingleton().getAudioMessageController().dispose();
		headerImageView = (ImageView) findViewById(R.id.swing_card);
		nameTextView = (TextView) findViewById(R.id.tv_nick);
		hangup = (Button) findViewById(R.id.btn_hangup_call);
		pickup = (Button) findViewById(R.id.btn_answer_call);
		refuse = (Button) findViewById(R.id.btn_refuse_call);
		iv_mute = (ImageView) findViewById(R.id.iv_mute);
		tv_tips = (TextView) findViewById(R.id.tv_tips);
		call_time=(Chronometer)findViewById(R.id.call_time);
		iv_handFree = (ImageView) findViewById(R.id.iv_handsfree);
		coming_callLayout = (LinearLayout) findViewById(R.id.ll_coming_call);
		layout_handsfree=(LinearLayout)findViewById(R.id.layout_handsfree);//免提 接通后才显示
		layout_mute=(LinearLayout)findViewById(R.id.layout_mute); //静音  接通后才显示
		layout_handsfree.setVisibility(View.INVISIBLE);
		layout_mute.setVisibility(View.INVISIBLE);
		//对方请求视频
		if(getIntent().hasExtra("event")) {
			RequestEvent event = (RequestEvent) getIntent().getSerializableExtra("event");
			if (event != null) {
				userId = event.requestID;
				loginID= event.getLoginID();
				clientType = event.clientType;
			}
		}
		GGApplication.getInstance().ringForCalling();

		if (StringHelper.isNullOrEmpty(userId)) {
			//我向对方发起视频
			userId = getIntent().getStringExtra("requestID");

			if(StringHelper.isNullOrEmpty(userId)){
				tv_tips.setText("未知requestID");
			}else{
				coming_callLayout.setVisibility(View.GONE);
				hangup.setBackgroundResource(R.drawable.call_cancel_bg);
				hangup.setVisibility(View.VISIBLE);
				Manager.getInstance().sendMediaCommunicate(userId, CommunicateMediaType.Audio, CommunicateType.Request, "",-1);
				tv_tips.setText("正在等待对方接受邀请");
			}
		}else {
			//对方发出请求 sourceID
			tv_tips.setText("邀请你语音通话");
			coming_callLayout.setVisibility(View.VISIBLE);
			tv_tips.setVisibility(View.GONE);
			hangup.setVisibility(View.GONE);
		}

		GGUser GGUser = ClientGlobalCache.getInstance().getUser(userId);
		if (GGUser != null) {
			nameTextView.setText(GGUser.getName());
			HeadImgHelper.setUserHeadImg(headerImageView, GGUser);
		}else {
			nameTextView.setText("未知用户");
		}

		iv_mute.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					//静音 关掉自己的麦克风，还可以听到对方的麦克风声音
					boolean isMute = iv_mute.isActivated();
					MultimediaManagerFactory.GetSingleton().setOutputAudio(isMute);//true :开起声音， false：静音
					iv_mute.setActivated(!isMute);

//					if (microphoneConnector != null) {
//						microphoneConnector.mute = !microphoneConnector.mute;
//						if (microphoneConnector.mute) {
//							iv_mute.setImageResource(R.drawable.mute_btn_pre);
//						} else {
//							iv_mute.setImageResource(R.drawable.mute_btn_nor);
//						}
//					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		});

		iv_handFree.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					if(currVolume==0){
						iv_handFree.setImageResource(R.drawable.hf_btn_pre);
						currVolume = AndroidUtil.OpenSpeaker(VoiceCallActivity.this);
					}else{
						iv_handFree.setImageResource(R.drawable.hf_btn_nor);
						AndroidUtil.CloseSpeaker(VoiceCallActivity.this,currVolume);
						currVolume=0;
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}});

		hangup.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				GGApplication.getInstance().stopRingForCalling();
				try {
					int destType =-1;
					if(clientType!=null) {
						destType = clientType.ordinal();
					}
					Manager.getInstance().sendMediaCommunicate(userId, CommunicateMediaType.Audio, CommunicateType.Terminate, "", destType);
					terminate("语音已中断!");
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		});

		pickup.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				GGApplication.getInstance().stopRingForCalling();
				GGUser destUser= ClientGlobalCache.getInstance().getUser4Cache(userId);
				if(destUser==null||destUser.getUserStatus()==UserStatus.OffLine)//对方离线了，直接提示挂断
				{
					terminate("对方已挂断");
					return;
				}
				int destType =-1;
				if(clientType!=null) {
					destType = clientType.ordinal();
				}
				coming_callLayout.setVisibility(View.GONE);
				hangup.setVisibility(View.VISIBLE);
				openConnector();
				Manager.getInstance().sendMediaCommunicate(userId, CommunicateMediaType.Audio, CommunicateType.Agree, "",destType);
				startTimer();
			}
		});

		refuse.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				GGApplication.getInstance().stopRingForCalling();
				int destType =-1;
				if(clientType!=null) {
					destType = clientType.ordinal();
				}
				Manager.getInstance().sendMediaCommunicate(userId, CommunicateMediaType.Audio, CommunicateType.Reject, "",destType);
				finish();
			}
		});

		//关闭免提
		AndroidUtil.CloseSpeaker(VoiceCallActivity.this,AndroidUtil.getCurrentVolume(VoiceCallActivity.this));
	}

	private Long hours ;
	private Long minitues ;
	private Long seconds ;
	Date startDate;
	private void startTimer () {
		startDate = new Date(System.currentTimeMillis());
		startDate=new Date();
		try {
			tv_tips.setVisibility(View.GONE);
			layout_handsfree.setVisibility(View.VISIBLE);
			layout_mute.setVisibility(View.VISIBLE);
			call_time.setVisibility(View.VISIBLE);
			call_time.setBase(SystemClock.elapsedRealtime());
			call_time.start();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 消息处理器的应用
	 */
	public Handler mHandler = new Handler() ;


	void setTimeValues(Date startTime, Date endTime) {
		// 按照传入的格式生成一个simpledateformate对象
		long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
		long nh = 1000 * 60 * 60;// 一小时的毫秒数
		long nm = 1000 * 60;// 一分钟的毫秒数
		long ns = 1000;// 一秒钟的毫秒数
		long diff;
		long day = 0;
		// 获得两个时间的毫秒时间差异
		diff = endTime.getTime()-startTime.getTime()
		;
		day = diff / nd;// 计算差多少天
		hours = diff % nd / nh;// 计算差多少小时
		minitues = diff % nd % nh / nm;// 计算差多少分钟
		seconds = diff % nd % nh % nm / ns;// 计算差多少秒
		// 输出结果
		System.out.println("时间相差：" + day + "天" + hours + "小时" + minitues
				+ "分钟" + seconds + "秒。");
	}


	Thread  thread2 ;

	private void openConnector() {
		try {
			if (thread2 != null) {
				thread2.interrupt();
			}
			thread2 = new Thread(new Runnable() {
				@Override
				public void run() {
					microphoneConnector = new MicrophoneConnector();
					microphoneConnector.beginConnect(loginID);
				}
			});
			thread2.start();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void onEventMainThread(CallEvent event) {
		if (event.isEcho) {
			terminate("已经在其它设备上做出了应答！");
		} else {
			if (!event.target.equals(userId) || event.mediaType != CommunicateMediaType.Audio) {
				return;
			}
			if (event.communicateType == CommunicateType.Agree) {
				agree(event);
			} else if (event.communicateType == CommunicateType.Reject) {
				terminate("对方拒绝您的语音邀请!");
			} else if (event.communicateType == CommunicateType.Terminate) {
				terminate("对方已挂断!");
			} else if (event.communicateType == CommunicateType.Busy) {
				terminate("对方忙线中!");
			}
		}
	}

	public void onEventMainThread(RequestEvent event) {
		if (event.mediaType == CommunicateMediaType.Offline) {
			this.clientType = event.clientType;
			if(clientType==null){
				terminate("已掉线，视频中断!");
				return;
			}
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					Manager.getInstance().sendMediaCommunicate(userId, CommunicateMediaType.Audio, CommunicateType.Terminate, "",clientType.ordinal());
					terminate("语音已中断!");
				}
			});
		}
	}

	public void onEventMainThread(UserEvent event) {
		if (event.status == UserStatus.OffLine&&event.userID.equals(userId)) {
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					terminate("对方已下线!");
				}
			});
		}
	}

	@Override
	protected void onDestroy() {
		try {

			closeConnectors();
			call_time.stop();
			MultimediaManagerFactory.GetSingleton().setOutputAudio(true);
			//关闭免提
			AndroidUtil.CloseSpeaker(VoiceCallActivity.this,currVolume);
			EventBus.getDefault().unregister(this);
			super.onDestroy();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void closeConnectors() {
		try {
			if (thread2 != null) {
				thread2.interrupt();
			}
			if (microphoneConnector != null) {
				microphoneConnector.disconnect();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 菜单、返回键响应
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		try {
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				Manager.getInstance().sendMediaCommunicate(userId, CommunicateMediaType.Audio, CommunicateType.Terminate, "",clientType.ordinal());
				terminate("语音已中断!");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return false;
	}

	private void agree(CallEvent event){
		GGApplication.getInstance().stopRingForCalling();
		userId = event.target;
		loginID = event.getTagetLoginID();
		clientType = event.clientType;
		openConnector();
		startTimer();
	}

	private void terminate(String message){
		GGApplication.getInstance().stopRingForCalling();
		Manager.getInstance().sendSystemMessage(userId,message,false);// 发送系统消息
		finish();
		ToastUtils.showLong(GGApplication.applicationContext, message);
	}
}

